const express = require('express');
const app = express()
const axios = require('axios');

// Please install OpenAI SDK first: `npm install openai`
const OpenAI = require("openai");
const apiKey = "sk-8bad29d07e6948df8196ef1ddc96512b"
const openai = new OpenAI({
    baseURL: 'https://api.deepseek.com',
    apiKey: apiKey
});

// 对话补全
app.post('/chat', async (req, res) => {
    // res.set('Content-Type', 'application/json')
    let sendContent = req.body.content

    const completion = await openai.chat.completions.create({
        messages: [{ role: "system", content: sendContent }],
        model: "deepseek-chat",
    });

    res.send({
        code: 200,
        data: {
            content: sendContent,
            deepseek: completion
        },
        msg: "操作成功"
    })
})
// 多轮对话
app.post('/chat/completions', async (req, res) => {
    // res.set('Content-Type', 'application/json')
    let sendMessages = req.body.messages

    const completion = await openai.chat.completions.create({
        messages: sendMessages,
        model: "deepseek-chat",
    });

    res.send({
        code: 200,
        data: {
            content: sendMessages,
            deepseek: completion
        },
        msg: "操作成功"
    })
})
// 可用模型列表
app.get('/models', async (req, res) => {
    // res.set('Content-Type', 'application/json')
    const models = await openai.models.list()
    for await (const model of models) {
        console.warn("可用模型列表", model);
    }

    res.send({
        code: 200,
        data: {
            models: models
        },
        msg: "操作成功"
    })
})
// 查询账号余额
app.get('/user/balance', (req, res) => {
    // res.set('Content-Type', 'application/json')
    let config = {
        method: 'get',
        maxBodyLength: Infinity,
        url: 'https://api.deepseek.com/user/balance',
        headers: {
            'Accept': 'application/json',
            'Authorization': `Bearer ${apiKey}`
        }
    }
    axios(config).then((response) => {
        res.send({
            code: 200,
            data: response.data,
            msg: "操作成功"
        })
    }).catch((error) => {
        res.send({
            code: 500,
            error: error.message,
            msg: "操作失败"
        })
    });
})

module.exports = app;